import React, { useState } from 'react';
import { TextField, Autocomplete } from '@mui/material';
import { Close as CloseIcon, ExpandMore as ExpandMoreIcon } from '@mui/icons-material';
import { bgLight } from '../../theme';
import Tooltip from './Tooltip';

interface FilterProps {
  value: string | null;
  handleFilterChange: (value: string | null) => void;
  options: string[];
  label?: string;
  [key: string]: any;
}

const Filter: React.FC<FilterProps> = ({
  value,
  handleFilterChange,
  options,
  label,
  ...others
}) => {
  const [open, setOpen] = useState(false);

  return (
    <Autocomplete
      open={open}
      onClose={() => setOpen(false)}
      onOpen={() => setOpen(true)}
      sx={{
        flex: 1,
        backgroundColor: bgLight,
        '& .MuiInput-underline:before': {},
        '& .MuiInput-underline:after': {},
      }}
      clearOnEscape
      autoComplete
      openOnFocus
      autoHighlight
      value={value === '' ? null : value}
      options={options}
      openText=""
      closeText=""
      clearText=""
      componentsProps={{
        clearIndicator: {
          children: (
            <Tooltip title="Clear" placement="top">
              <CloseIcon fontSize="small" />
            </Tooltip>
          ),
        },
        popupIndicator: {
          children: (
            <Tooltip title={open ? 'Close' : 'Open'} placement="top">
              <ExpandMoreIcon />
            </Tooltip>
          ),
        },
      }}
      ListboxProps={{
        sx: {
          color: 'white',
          maxHeight: '20vh',
        },
      }}
      onChange={(event, newValue) => handleFilterChange(newValue)}
      renderInput={(params) => (
        <TextField {...params} variant="filled" label={label} />
      )}
      {...others}
    />
  );
};

export default Filter;

